/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.chl.cid.sasanshop;

import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author rhodinj
 */
@FacesValidator(value="emailValidator")
public class EmailValidator implements Validator {

    private Pattern pattern;
    private Matcher matcher;

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String componentValue = value.toString();

        pattern = Pattern.compile(".+@.+\\.[a-z]+");
        matcher = pattern.matcher(componentValue);

        if(!matcher.find()) {
            String message = MessageFormat.format(
                             "{0} is not a valid e-mail address", componentValue);

            FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message);
            throw new ValidatorException(facesMessage);
        }
    }

}
